package api

import (
	"go-weiqi-system/config"
	"go-weiqi-system/internal/models"
	"go-weiqi-system/internal/utils"

	"github.com/gin-gonic/gin"
)

type RankingController struct{}

// LevelRanking 等级榜
func (ctrl *RankingController) LevelRanking(c *gin.Context) {
	var param models.PageParam
	if err := c.ShouldBindQuery(&param); err != nil {
		param.Page = 1
		param.PageSize = 10
	}

	var users []models.User
	var total int64

	db := config.DB.Model(&models.User{}).Where("status = ?", 1)

	db.Count(&total)
	db.Order("level_score desc, id asc").
		Offset(param.GetOffset()).
		Limit(param.GetPageSize()).
		Find(&users)

	utils.Success(c, models.PageResponse{
		List:     users,
		Total:    total,
		Page:     param.GetPage(),
		PageSize: param.GetPageSize(),
	})
}

// ContributionRanking 贡献榜
func (ctrl *RankingController) ContributionRanking(c *gin.Context) {
	var param models.PageParam
	if err := c.ShouldBindQuery(&param); err != nil {
		param.Page = 1
		param.PageSize = 10
	}

	var users []models.User
	var total int64

	db := config.DB.Model(&models.User{}).Where("status = ?", 1)

	db.Count(&total)
	db.Order("contribution_score desc, id asc").
		Offset(param.GetOffset()).
		Limit(param.GetPageSize()).
		Find(&users)

	utils.Success(c, models.PageResponse{
		List:     users,
		Total:    total,
		Page:     param.GetPage(),
		PageSize: param.GetPageSize(),
	})
}

// WinRateRanking 胜率榜
func (ctrl *RankingController) WinRateRanking(c *gin.Context) {
	var param models.PageParam
	if err := c.ShouldBindQuery(&param); err != nil {
		param.Page = 1
		param.PageSize = 10
	}

	var users []models.User
	var total int64

	db := config.DB.Model(&models.User{}).
		Where("status = ? AND total_games >= ?", 1, 10)

	db.Count(&total)
	db.Order("win_rate desc, id asc").
		Offset(param.GetOffset()).
		Limit(param.GetPageSize()).
		Find(&users)

	utils.Success(c, models.PageResponse{
		List:     users,
		Total:    total,
		Page:     param.GetPage(),
		PageSize: param.GetPageSize(),
	})
}
